package cn.kn.sys.service.impl;

import cn.kn.common.exception.CustomException;
import cn.kn.common.model.PageBean;
import cn.kn.common.model.PageResult;
import cn.kn.common.model.R;
import cn.kn.common.model.RCode;
import cn.kn.common.utils.CopyBean;
import cn.kn.sys.mapper.RoleMapper;
import cn.kn.sys.model.Role;
import cn.kn.sys.model.RoleExample;
import cn.kn.sys.service.RoleService;
import cn.kn.sys.vo.RoleVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author WangJiang
 * @create 2020-12-04 15:35
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends BaseService implements RoleService {
    private final RoleMapper roleMapper;

    @Override
    public R list(String name, PageBean pageBean) {

        RoleExample example=new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria().andIsdelEqualTo(false);
        if(!StringUtils.isEmpty(name)){
            criteria.andNameLike("%"+name+"%");
        }
        PageHelper.startPage(pageBean.getPage(),pageBean.getSize());
        PageInfo<Role> info =new PageInfo<>(roleMapper.selectByExample(example));

//        List<RoleVo> roleVos=new ArrayList<>();


        return R.ok(new PageResult<>(info.getTotal(), CopyBean.copyBean(info.getList(),RoleVo::new)));
    }

    @Override
    public R add(RoleVo roleVo) {
        exist(roleVo);
        roleMapper.insertSelective(CopyBean.copyBean(roleVo,Role::new));
        return R.ok();
    }

    @Override
    public R del(Long id) {
        RoleExample roleExample=new RoleExample();
        Role role=new Role();
        role.setIsdel(true);
        role.setId(id);
        roleMapper.updateByPrimaryKeySelective(role);
        return R.ok();
    }

    @Override
    public R edit(Long id, RoleVo roleVo) {
        roleVo.setId(id);
        roleMapper.updateByPrimaryKeySelective(CopyBean.copyBean(roleVo,Role::new));
        return R.ok();
    }

    @Override
    public R editStatus(Long id, Boolean isstop) {
        Role role = new Role();
        role.setId(id);
        role.setIsstop(isstop);
        roleMapper.updateByPrimaryKeySelective(role);
        return R.ok();
    }

    @Override
    public R all() {
        return R.ok(roleMapper.selectByExample(null));
    }


    private void exist(RoleVo roleVo) {
        RoleExample roleExample=new RoleExample();
        roleExample.createCriteria()
                    .andIsdelEqualTo(false)
                    .andNameEqualTo(roleVo.getName());
        List<Role> roles=roleMapper.selectByExample(roleExample);
        if(!CollectionUtils.isEmpty(roles)){
            throw new CustomException(RCode.ROLE_NAMER_EPEAT);
        }
    }
}
